package com.sh.pangea.dsa.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.LargeValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.sh.lib.dsa.bean.analyzeresult.LinearItem;
import com.sh.pangea.dsa.R;
import com.sh.pangea.dsa.Utils.AnalyzeIntentUtil;
import com.sh.pangea.dsa.Utils.AnalyzeStringUtil;
import com.sh.pangea.dsa.Utils.SildingFinishLayout;
import com.sh.pangea.dsa.Utils.XYMarkerView;
import com.sh.pangea.dsa.bean.AnalyzeResult;
import com.sh.pangea.dsa.bean.Level;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by TianGenhu on 2016/10/9.
 */

public class LineChartActivity2 extends Activity {
    private BarChart barChart;
    private final String TAG = "TGH";
    private LineChart tvChannelLineChart;
    private PieChart pieChart;
    @BindView(R.id.analyze_linearlayout)
    LinearLayout analyze_linearlayout;
    @BindView(R.id.sildingFinishLayout)
    SildingFinishLayout sildingFinishLayout;
    @BindView(R.id.linar_chart_layout)
    LinearLayout linarChartLayout;
    @BindView(R.id.bar_chart_layout)
    LinearLayout barChartLayout;
    @BindView(R.id.line_chart_title)
    TextView lineChartTitle;
    @BindView(R.id.pie_chart_layout)
    LinearLayout pieChartLayout;


    private AnalyzeResult mAnalyzeResult = null;
    private Entry mEntry;
    private final ViewGroup.LayoutParams mLineChartLayout = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);


    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (mAnalyzeResult != null) {
                        String nameGraph = mAnalyzeResult.getTitleGraph();
                        if (nameGraph == null) {
                            nameGraph = "";
                        }
                        Log.i(TAG, "handleMessage    nameGraph : " + nameGraph + "     " + mAnalyzeResult.getyForGraph());
                        getXString();
                        showIconType(mAnalyzeResult.getyForGraph(), nameGraph);
                        lineChartTitle.setText(nameGraph);
                    } else {
                        Log.i(TAG, "handleMessage: mAnalyzeResult is null ");
                    }
                    break;

                case 3:
                    switch (AnalyzeIntentUtil.getInstance(LineChartActivity2.this).getIconType()) {
                        case AnalyzeIntentUtil.LINAR_CHART://初始化折线图
                            linarChartLayout.removeAllViews();
                            tvChannelLineChart = new LineChart(LineChartActivity2.this);
                            tvChannelLineChart.setLayoutParams(mLineChartLayout);
                            setLineChart(tvChannelLineChart);
                            linarChartLayout.addView(tvChannelLineChart);
                            break;
                        case AnalyzeIntentUtil.BAR_CHART://初始化柱状图
                            barChartLayout.removeAllViews();
                            barChart = new BarChart(LineChartActivity2.this);
                            barChart.setLayoutParams(mLineChartLayout);
                            setBarChart(barChart);
                            barChartLayout.addView(barChart);
                            break;
                        case AnalyzeIntentUtil.PIE_CHART://初始化扇形图
                            pieChartLayout.removeAllViews();
                            pieChart = new PieChart(LineChartActivity2.this);
                            pieChart.setLayoutParams(mLineChartLayout);
                            setPieChart(pieChart);
                            pieChartLayout.addView(pieChart);
                            break;
                        default:
                            Log.i(TAG, "handleMessage:初始化组件没有匹配项");
                            break;
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //一直显示手机状态栏
        this.findViewById(Window.ID_ANDROID_CONTENT);
        setContentView(R.layout.activity_tv_channel_2);
        ButterKnife.bind(this);
        initView();
        mHandler.sendEmptyMessage(3);
        getIntetn();
    }

    private void getIntetn() {
        Intent intent = this.getIntent();
        mAnalyzeResult = intent.getParcelableExtra("result");
        String name = intent.getStringExtra("name");
        mAnalyzeResult.setTitleGraph(name);
        Log.i(TAG, "getIntetn: " + mAnalyzeResult);
        mHandler.sendEmptyMessage(0);
    }


    private void setLineChart(LineChart tvChannelLineChart) {
        //此方法设置为false时图像拉大后，用手指不能左右上下拖动
        tvChannelLineChart.setDragEnabled(true);
        //去掉图标的标志
        tvChannelLineChart.getDescription().setEnabled(false);
        //禁止水平方向拖拽
        tvChannelLineChart.setScaleXEnabled(true);
        //禁止垂直方向拖拽
        tvChannelLineChart.setScaleYEnabled(false);
        //画图标的边框
        tvChannelLineChart.setDrawBorders(true);
        //设置图标边框的线的宽度
        //tvChannelLineChart.setBorderWidth(2f);
        //设置数据为空时显示的描述文字
        tvChannelLineChart.setNoDataText("暂时没有数据！");
        //设置数据为空时显示的描述文字的颜色
        tvChannelLineChart.setNoDataTextColor(getResources().getColor(R.color.colorPrimaryDark));
        //设置图表的背景颜色 不知道为什么不起作用
        //tvChannelLineChart.setGridBackgroundColor(getResources().getColor(R.color.colorSub));
        //
        //tvChannelLineChart.getYChartMin(false);

        // 设置Legend启用或禁用
        Legend legend = tvChannelLineChart.getLegend();
        legend.setEnabled(true);
        legend.setTextSize(12);
        legend.setTextColor(getResources().getColor(R.color.colorAccent));


        XAxis xAxis = tvChannelLineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day
        xAxis.setLabelCount(7);
        xAxis.setValueFormatter(mIAxisValueFormatter_X);
        //设置x轴字体显示角度,即X轴上文字呈现斜着显示
        xAxis.setLabelRotationAngle(-20);
        //设置X轴的位置TOP, BOTTOM, BOTH_SIDED, TOP_INSIDE, BOTTOM_INSIDE
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


        YAxis leftAxis = tvChannelLineChart.getAxisLeft();
        leftAxis.setInverted(false);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        leftAxis.setValueFormatter(mIAxisValueFormatter_Y);
        YAxis rightAxis = tvChannelLineChart.getAxisRight();
        rightAxis.setEnabled(true);
        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        rightAxis.setValueFormatter(mIAxisValueFormatter_Y_right);
        // get the legend (only possible after setting data)
        Legend l = tvChannelLineChart.getLegend();
        // modify the legend ...
        l.setForm(Legend.LegendForm.LINE);
        // dont forget to refresh the drawing
        tvChannelLineChart.invalidate();
        tvChannelLineChart.animateY(3000);
//        XYMarkerView mv = new XYMarkerView(this, mIAxisValueFormatter_X);
//        mv.setChartView(tvChannelLineChart); // For bounds control
//        tvChannelLineChart.setMarker(mv); // Set the marker to the chart

    }


    private void setBarChart(BarChart barChart) {
        //Set this to true to enable dragging (moving the chart with the finger) for the chart (this does not effect scaling).
        //此方法设置为false时图像拉大后，用手指不能左右上下拖动
        barChart.setDragEnabled(true);
        barChart.setDrawBarShadow(false);
        //柱状图上面的数值显示在柱子上面还是柱子里面
        barChart.setDrawValueAboveBar(true);
        barChart.getDescription().setEnabled(false);
        //禁止水平方向拖拽
        barChart.setScaleXEnabled(true);
        //禁止垂直方向拖拽
        barChart.setScaleYEnabled(false);
        //取消双击放大功能
        barChart.setDoubleTapToZoomEnabled(false);
        //画图标的边框
        barChart.setDrawBorders(true);
        //设置图标边框的线的宽度
        //barChart.setBorderWidth(2f);
        barChart.animateY(3000);
        // if more than 60 entries are displayed in the chart, no values will be drawn
        barChart.setMaxVisibleValueCount(60);
        // scaling can now only be done on x- and y-axis separately
//        barChart.setPinchZoom(false);
        barChart.setDrawGridBackground(false);
        barChart.setFitBars(true);
        //设置数据为空时显示的描述文字
        barChart.setNoDataText("暂时没有数据！");
        //设置数据为空时显示的描述文字的颜色
        barChart.setNoDataTextColor(getResources().getColor(R.color.colorPrimaryDark));
        //设置图表的背景颜色  不知道为什么不起作用
        //barChart.setGridBackgroundColor(getResources().getColor(R.color.colorSub));


        // 设置Legend启用或禁用
        Legend legend = barChart.getLegend();
        legend.setEnabled(false);
        legend.setTextColor(getResources().getColor(R.color.colorAccent));
        legend.setWordWrapEnabled(true);

        XAxis xAxisc = barChart.getXAxis();
        xAxisc.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxisc.setDrawGridLines(false);
        // only intervals of 1 day  即：每柱只显示一个值
        xAxisc.setGranularity(1f);
        xAxisc.setLabelCount(7);
        xAxisc.setValueFormatter(mIAxisValueFormatter_X);
//        xAxisc.setAxisMinimum(0f);
        xAxisc.setDrawAxisLine(true);
        //设置x轴字体显示角度,即X轴上文字呈现斜着显示
        xAxisc.setLabelRotationAngle(-20);
        //设置X轴的位置TOP, BOTTOM, BOTH_SIDED, TOP_INSIDE, BOTTOM_INSIDE
        xAxisc.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置x轴的颜色
        xAxisc.setAxisLineColor(getResources().getColor(R.color.colorAccent));
//
        YAxis leftAxisc = barChart.getAxisLeft();
        leftAxisc.setLabelCount(8, false);
        leftAxisc.setValueFormatter(mIAxisValueFormatter_Y);
//        leftAxisc.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxisc.setSpaceTop(15f);
        leftAxisc.setAxisMinimum(0f);

        YAxis rightAxisc = barChart.getAxisRight();
        //设置右边Y轴是否显示数据
        rightAxisc.setEnabled(false);
        rightAxisc.setSpaceTop(15f);
        rightAxisc.setValueFormatter(mIAxisValueFormatter_Y);
        rightAxisc.setAxisMinimum(0f);

        Legend lc = barChart.getLegend();
        lc.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        lc.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        lc.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        lc.setDrawInside(false);
        lc.setForm(Legend.LegendForm.SQUARE);
        lc.setFormSize(9f);
        lc.setTextSize(6f);
        lc.setXEntrySpace(4f);

//        XYMarkerView mv = new XYMarkerView(this, mIAxisValueFormatter_X);
//        mv.setChartView(barChart); // For bounds control
//        barChart.setMarker(mv); // Set the marker to the chart
        barChart.setOnChartValueSelectedListener(mOnChartValueSelectedListener);

    }


    private void setPieChart(PieChart pieChart) {
        //用自带的百分比算法
        pieChart.setUsePercentValues(true);
        pieChart.getDescription().setEnabled(false);
        //设置整个饼状图是空心还是实心
        pieChart.setDrawHoleEnabled(false);
        pieChart.setExtraOffsets(20f, 5.f, 20f, 5.f);
        //图标log显示在中心
        pieChart.setDrawCenterText(false);
        /**
         *触摸是否可以旋转以及松手后旋转的度数
         */
        pieChart.setRotationAngle(300);
        // enable rotation of the chart by touch
        pieChart.setRotationEnabled(true);
        pieChart.setHighlightPerTapEnabled(true);
        //饼形图上是否显示每个模块的X轴的值
        pieChart.setDrawEntryLabels(false);
        pieChart.animateX(1000);
        //设置数据为空时显示的描述文字
        pieChart.setNoDataText("暂时没有数据！");
        Legend l = pieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(true);
        l.setEnabled(true);


//        //点击没柱显示数据
//        XYMarkerViewPiePoylineChart mv = new XYMarkerViewPiePoylineChart(this, mIAxisValueFormatter_X);
//        mv.setChartView(pieChart); // For bounds control
//        pieChart.setMarker(mv); // Set the marker to the chart
//        pieChart.setOnChartValueSelectedListener(mOnChartValueSelectedListener);

    }

    private void initView() {
        sildingFinishLayout.setOnSildingFinishListener(new SildingFinishLayout.OnSildingFinishListener() {
            @Override
            public void onSildingFinish() {
                LineChartActivity2.this.finish();
            }
        });
        // touchView要设置到ListView上面
        sildingFinishLayout.setTouchView(linarChartLayout);
        sildingFinishLayout.setTouchView(barChartLayout);
        sildingFinishLayout.setTouchView(analyze_linearlayout);
    }

    private final OnChartValueSelectedListener mOnChartValueSelectedListener = new OnChartValueSelectedListener() {
        @Override
        public void onValueSelected(Entry e, Highlight h) {
            mEntry = e;
            delayedHide(mHandler, 6);
        }

        @Override
        public void onNothingSelected() {
            Log.i("TGH", "onNothingSelected: ");
        }
    };


    private final IAxisValueFormatter mIAxisValueFormatter_X = new IAxisValueFormatter() {

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            String a = "";
            switch (AnalyzeIntentUtil.getInstance(LineChartActivity2.this).getIconType()) {
                case AnalyzeIntentUtil.BAR_CHART://柱状图
                    a = ((int) value) + 1 + "";
                    break;
                case AnalyzeIntentUtil.LINAR_CHART://折线图
                    if (xForGraph != null) {
                        a = xForGraph.get(Math.min(Math.max((int) value, 0), xForGraph.size() - 1));
                    }
                    break;
                case AnalyzeIntentUtil.PIE_CHART://扇形图
                    break;
                default:
                    break;
            }
            return a;
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    };

    private boolean has_K = false;
    private final DecimalFormat mFormat = new DecimalFormat("###,###,###,##0.0");
    private final IAxisValueFormatter mIAxisValueFormatter_Y = new IAxisValueFormatter() {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            String s;
            if (mFormat != null) {
                s = mFormat.format(value);
            } else {
                s = null;
            }
            return s;
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    };

    private final IAxisValueFormatter mIAxisValueFormatter_Y_right = new IAxisValueFormatter() {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            String s;
            if (mFormat != null) {
                if (has_K) {
                    int l = levelValue / 1000;
                    String s1 = String.valueOf(l);
                    s1 = s1.substring(1);
                    s = mFormat.format(value) + s1 + " K";
                } else {
                    s = mFormat.format(value);
                }
            } else {
                s = null;
            }
            return s;
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    };

    private List<Level> mLevel = null;

    /**
     * 获取最大值
     **/
    private void setNeighborhoodComparison(List<LinearItem> linearItems, String nameGraph) {
        Comparator comp = new Comparator() {
            public int compare(Object o1, Object o2) {
                Integer p1 = (Integer) o1;
                Integer p2 = (Integer) o2;
                if (p1 < p2)
                    return -1;
                else if (p1 == p2)
                    return 0;
                else if (p1 > p2)
                    return 1;
                return 0;
            }
        };

        List<Integer> maxDataList = new ArrayList<>();
        mLevel = new ArrayList<>();
        List<Integer> data = null;
        LinearItem linearItem = null;
        for (int a = 0; a < linearItems.size(); a++) {
            linearItem = linearItems.get(a);
            data = linearItem.getData();
            if (data != null) {
                Integer max = (Integer) Collections.max(data, comp);
                Integer min = (Integer) Collections.min(data, comp);
                String name = linearItem.getName();
                mLevel.add(new Level(max, name, data));
                maxDataList.add(a, max);
                Log.i(TAG, "generateDataLine 最大值  : " + max + "     " + min);
            }
        }

        if (maxDataList.size() > 0) {
            Integer min = (Integer) Collections.min(maxDataList, comp);
            for (int m = 0; m < mLevel.size(); m++) {
                Level l = mLevel.get(m);
                l.setMin(min);
            }
        }
        generateDataLine(linearItems, mLevel);
    }


    private int levelValue = 0;

    /**
     * generates a random ChartData object with just one DataSet
     */
    public void generateDataLine(List<LinearItem> linearItems, List<Level> mLevel) {
        if (linearItems != null && linearItems.size() > 0) {
            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            LineDataSet set1;
            for (int a = 0; a < linearItems.size(); a++) {
                ArrayList<Entry> yVals1 = new ArrayList<Entry>();
                LinearItem linearItem = linearItems.get(a);
                String name = linearItem.getName();
                List<Integer> data = linearItem.getData();
                if (data != null) {
                    for (int i = 0; i < data.size(); i++) {
                        float i1 = data.get(i);
                        int levelByName = getLevelByName(mLevel, name);
                        if (i1 > 1000) {
                            has_K = true;
                            levelValue = levelByName;
                        }
                        i1 = i1 / levelByName;
                        Entry entry = new Entry(i, i1);
                        entry.setLevel(levelByName);
                        entry.setName(name);
                        yVals1.add(entry);
                    }
                    if (tvChannelLineChart.getData() != null &&
                            tvChannelLineChart.getData().getDataSetCount() > 0) {
                        set1 = (LineDataSet) tvChannelLineChart.getData().getDataSetByIndex(a);
                        set1.setValues(yVals1);
                    } else {
                        set1 = new LineDataSet(yVals1, name);
                        if (a % 2 == 0) {
                            Log.i("TGH", "setData: " + a);
                            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                        } else {
                            set1.setAxisDependency(YAxis.AxisDependency.RIGHT);

                        }
                        int number = AnalyzeStringUtil.getInstance().getNumber(a);
                        set1.setColor(AnalyzeStringUtil.getInstance().COLORS[number]);
                        set1.setFillColor(AnalyzeStringUtil.getInstance().COLORS[number]);
                        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                        set1.setCircleColor(AnalyzeStringUtil.getInstance().COLORS[number]);
                        set1.setLineWidth(2f);
                        set1.setCircleRadius(3f);
                        set1.setFillAlpha(65);

                        set1.setHighLightColor(Color.rgb(244, 117, 117));
                        set1.setDrawCircleHole(false);
                        set1.setDrawValues(false);
                        dataSets.add(set1); // add the datasets
                    }
                }
            }
            if (tvChannelLineChart.getData() != null &&
                    tvChannelLineChart.getData().getDataSetCount() > 0) {
                tvChannelLineChart.getData().notifyDataChanged();
                tvChannelLineChart.notifyDataSetChanged();
            } else {
                // create a data object with the datasets
                LineData data = new LineData(dataSets);
                data.setValueTextColor(Color.RED);
                data.setValueTextSize(9f);
                data.setValueFormatter(new LargeValueFormatter());
                // set data
                tvChannelLineChart.setData(data);
            }
        } else {
            Log.i(TAG, "generateDataLine: linearItems list is null ");
        }

        //点击显示数据组件
        XYMarkerView mv = new XYMarkerView(this, mIAxisValueFormatter_X);
        mv.setChartView(tvChannelLineChart); // For bounds control
        tvChannelLineChart.setMarker(mv); // Set the marker to the chart
    }

    private int getLevelByName(List<Level> data, String name) {
        int l = 0;
        Level level = null;
        for (int i = 0; i < data.size(); i++) {
            level = data.get(i);
            if (level.getName().equals(name)) {
                l = level.getLevel();
                break;
            }
        }
        return l;
    }

    /**
     * generates a random ChartData object with just one DataSet
     */
    private void generateDataBar(List<LinearItem> linearItems, String nameGraph) {
        if (linearItems != null && linearItems.size() > 0) {
            LinearItem linearItem = linearItems.get(linearItems.size() - 1);
            if (linearItem != null) {
                List<Integer> data = linearItem.getData();
                has_K = false;
                ArrayList<BarEntry> entries = new ArrayList<>();
                //String[] split = AnalyzeStringUtil.getInstance().getStringArray(cnt);
                if (data != null && data.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        int i1 = data.get(i);
                        if (i1 > 1000) {
                            has_K = true;
                        }
                        entries.add(new BarEntry(i, i1));
                    }
                    BarDataSet dSet;
                    if (barChart.getData() != null &&
                            barChart.getData().getDataSetCount() > 0) {
                        barChart.getXAxis().setAxisMinimum(0f);
                        barChart.getXAxis().setAxisMaximum(15f);
                        dSet = (BarDataSet) barChart.getData().getDataSetByIndex(0);
                        dSet.setValues(entries);
                        barChart.getData().notifyDataChanged();
                        barChart.notifyDataSetChanged();
                        Log.i(TAG, "generateDataBar: 走了柱状的数据缓存");
                        barChart.invalidate();
                    } else {
                        dSet = new BarDataSet(entries, nameGraph);
                        dSet.setColors(ColorTemplate.VORDIPLOM_COLORS);
                        dSet.setHighLightAlpha(255);
                        dSet.setDrawValues(true);
                        //设置点击后的透明度 数值是0~99;
                        dSet.setHighLightAlpha(37);

                        BarData cd = new BarData(dSet);
                        cd.setBarWidth(0.9f);
                        cd.setValueTextSize(10f);
                        // set data
                        barChart.setData(cd);
                        //需要在设置数据源后生效
                        //barChart.setVisibleXRangeMaximum(8);
                        Log.i(TAG, "generateDataBar: 柱状图没有数据缓存");
                    }

                } else {
                    Log.i(TAG, "generateDataBar: data is null");
                }
            }
        } else {
            Log.i(TAG, "generateDataBar: linearItems list is null");
        }
    }


    /**
     * 获取千分之一值
     */
    private float getMil(List<LinearItem> linearItems) {
        float num = 0;
        if (linearItems != null && linearItems.size() > 0) {
            for (int i = 0; i < linearItems.size(); i++) {
                LinearItem linearItem = linearItems.get(i);
                int yAxis = linearItem.getYAxis();
                num = yAxis + num;
            }
        }
        Log.i(TAG, "getMil   num: " + num + "  千分之一 ： " + num / 100);
        return num / 100;
    }


    List<LinearItem> popWindPieList = new ArrayList<>();

    private List<LinearItem> getManagePieDate(List<LinearItem> linearItems) {
        popWindPieList.clear();
        float mil = getMil(linearItems);
        int num = 0;
        List<LinearItem> list = new ArrayList<>();
        if (linearItems != null && linearItems.size() > 0) {
            LinearItem linearItem = null;
            for (int i = 0; i < linearItems.size(); i++) {
                linearItem = linearItems.get(i);
                int yAxis = linearItem.getYAxis();
                if (yAxis <= mil) {
                    num = yAxis + num;
                    popWindPieList.add(linearItem);
                } else {
                    list.add(linearItem);
                }
            }
            LinearItem item = new LinearItem();
            item.setName("其他");
            if (num > mil) {
                item.setYAxis(num);
                list.add(item);
            } else {
                if (num > 0) {
                    item.setYAxis((int) mil);
                    item.setName("其他");
                    item.setType("@" + num);
                    list.add(item);
                }
            }
        }
        return list;
    }

    private void generateDataPie(List<LinearItem> linearItems) {
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        if (linearItems != null && linearItems.size() > 0) {
            for (int i = 0; i < linearItems.size(); i++) {
                LinearItem linearItem = linearItems.get(i);
                entries.add(new PieEntry(linearItem.getYAxis(), linearItem.getName()));
            }
            PieDataSet dataSet = new PieDataSet(entries, /*nameGraph*/"");
            dataSet.setSliceSpace(3f);
            dataSet.setSelectionShift(5f);
            // add a lot of colors
            ArrayList<Integer> colors = new ArrayList<Integer>();
            for (int c : ColorTemplate.VORDIPLOM_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.JOYFUL_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.COLORFUL_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.LIBERTY_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.PASTEL_COLORS)
                colors.add(c);

            colors.add(ColorTemplate.getHoloBlue());
            dataSet.setColors(colors);
            //dataSet.setSelectionShift(0f);

            dataSet.setValueLinePart1OffsetPercentage(80.f);
            //设置每个扇形数值上黑线的长度
            dataSet.setValueLinePart1Length(0.5f);
            dataSet.setValueLinePart2Length(0.5f);
            //dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
            dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

            PieData data = new PieData(dataSet);
            Log.i(TAG, "大图  generateDataPie:   " + entries);
            //设置百分比显示
            data.setValueFormatter(new PercentFormatter(entries));
            data.setValueTextSize(8f);
            data.setValueTextColor(Color.BLACK);
            pieChart.setData(data);

            // undo all highlights
            pieChart.highlightValues(null);
            pieChart.invalidate();
        }
    }

    private List<String> xForGraph = new ArrayList<>();

    private void getXString() {
        if (mAnalyzeResult != null) {
            List<String> xList = mAnalyzeResult.getxForGraph();
            if (xList != null && xList.size() > 0) {
                xForGraph = xList;
            } else {
                Log.i(TAG, "getXString: xList is null");
                xForGraph = null;
            }
        } else {
            Log.i(TAG, "getXString: mAnalyzeResult is null");
            xForGraph = null;
        }

    }

    private void showIconType(List<LinearItem> linearItems, String nameGraph) {
        if (linearItems != null && linearItems.size() > 0) {
            switch (AnalyzeIntentUtil.getInstance(LineChartActivity2.this).getIconType()) {
                case AnalyzeIntentUtil.LINAR_CHART://折线图
//                    generateDataLine(linearItems, nameGraph);
                    setNeighborhoodComparison(linearItems, nameGraph);
                    barChartLayout.setVisibility(View.GONE);
                    pieChartLayout.setVisibility(View.GONE);
                    linarChartLayout.setVisibility(View.VISIBLE);
                    break;
                case AnalyzeIntentUtil.BAR_CHART://柱状图
                    generateDataBar(linearItems, nameGraph);
                    linarChartLayout.setVisibility(View.GONE);
                    pieChartLayout.setVisibility(View.GONE);
                    barChartLayout.setVisibility(View.VISIBLE);
                    break;
                case AnalyzeIntentUtil.PIE_CHART://扇形图
                    linearItems = getManagePieDate(linearItems);
                    generateDataPie(linearItems);
                    linarChartLayout.setVisibility(View.GONE);
                    pieChartLayout.setVisibility(View.VISIBLE);
                    barChartLayout.setVisibility(View.GONE);
                    break;
                default:
                    Log.i(TAG, "showIconType: 没有匹配的图表");
                    break;
            }
        } else {
            Log.i(TAG, "showIconType: linearItems is null");
        }
    }

    /**
     * 返回
     **/
    @OnClick(R.id.analyze_back)
    public void onBackClick(View view) {
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AnalyzeIntentUtil instance = AnalyzeIntentUtil.getInstance(this);
        // TODO: 2016/12/28 暂时注掉
//        instance.setWeekly(instance.getTimeWeek()+"");
//        instance.setQueryDate(instance.getTimeStr());
    }

    /**
     * 通知指定的控制栏进行延时隐藏，适合此方法的参数的都可使用此方法
     **/
    private void delayedHide(Handler handler, int what) {
        if (handler != null) {
            while (handler.hasMessages(what)) {
                handler.removeMessages(what);
            }
            handler.sendEmptyMessageDelayed(what, 300);
        } else {
            Log.i(TAG, "delayedHide: handler is null");
        }

    }


}
